// Connect.cpp : Implementation of CConnect

#include "stdafx.h"
#include "Connect.h"

void CConnect::StartSyncTool()
{
	ULONG const arraysize = 1024;
	WCHAR   pszUrl[arraysize];
	CRegKey RegKey;

	// Open key
	if(RegKey.Open(HKEY_CURRENT_USER, L"Software\\OutlookContactsSync") != ERROR_SUCCESS)
	{
		MessageBox(
				NULL,
				(LPCWSTR)L"Cannot start Outlook Contacts Sync tool.\n\nMissing registry key 'HKCU\\Software\OutlookContactsSync'.",
				(LPCWSTR)L"Error",
				MB_ICONERROR | MB_OK
			);

		return;
	}

	ULONG actualsize = arraysize;

	if(RegKey.QueryStringValue(L"SyncToolStartUrl", pszUrl, &actualsize) != ERROR_SUCCESS)
	{
		MessageBox(
				NULL,
				(LPCWSTR)L"Cannot start Outlook Contacts Sync tool.\n\nCannot read value from registry key 'HKCU\\Software\OutlookContactsSync\\SyncToolStartUrl'.",
				(LPCWSTR)L"Error",
				MB_ICONERROR | MB_OK
			);

		return;
	}

	// Close key
	if(RegKey.Close() != ERROR_SUCCESS)
	{
	  // Ignore error
	}

	ExecuteUrl(pszUrl);
}

bool CConnect::ExecuteUrl(LPCWSTR url)
{
	SHELLEXECUTEINFOW ExecuteInfo;
    
    memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
    
    ExecuteInfo.cbSize       = sizeof(ExecuteInfo);
    ExecuteInfo.fMask        = 0;                
    ExecuteInfo.hwnd         = 0;                
    ExecuteInfo.lpVerb       = L"open";                      // Operation to perform
    ExecuteInfo.lpFile       = url;               // Application name that start with http:// will open the default browser
    ExecuteInfo.lpDirectory  = 0;                           // Default directory
    ExecuteInfo.nShow        = SW_SHOW;
    ExecuteInfo.hInstApp     = 0;
    
    if(ShellExecuteEx(&ExecuteInfo) == FALSE)
	{
		DWORD errorCode = GetLastError();

		int const arraysize = 200;
		WCHAR pszDest[arraysize]; 
		size_t cbDest = arraysize * sizeof(WCHAR);

		LPCWSTR pszFormat = L"Starting Contacts Sync tool failed (error %d).";

		HRESULT hr = StringCbPrintfW(pszDest, cbDest, pszFormat, errorCode);

		int msgboxID = MessageBox(
				NULL,
				(LPCWSTR) pszDest,
				(LPCWSTR)L"Error",
				MB_ICONERROR | MB_OK
			);

		return false;
	}
	else 
	{
		return true;
	}
}


// CConnect
